<template>
  <el-dialog
    :model-value="visible"
    title="用户详情"
    width="800px"
    :close-on-click-modal="false"
    @update:model-value="$emit('update:visible', $event)"
  >
    <div v-if="user" class="user-detail">
      <!-- 用户基本信息 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <div class="user-avatar">
              <el-avatar :size="80" :src="user.avatar">
                {{ user.name?.charAt(0) }}
              </el-avatar>
            </div>
            <div class="user-info">
              <h3>{{ user.name }}</h3>
              <div class="user-meta">
                <el-tag :type="getRoleType(user.role)" size="large">
                  {{ translateRole(user.role) }}
                </el-tag>
                <el-tag :type="getStatusType(user.status)" size="large">
                  {{ translateStatus(user.status) }}
                </el-tag>
              </div>
            </div>
          </div>
        </template>

        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户ID">
            {{ user.id }}
          </el-descriptions-item>
          <el-descriptions-item label="用户名">
            {{ user.username }}
          </el-descriptions-item>
          <el-descriptions-item label="邮箱">
            {{ user.email }}
          </el-descriptions-item>
          <el-descriptions-item label="手机号">
            {{ user.phone || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="部门">
            {{ user.department || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="职位">
            {{ user.position || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDate(user.createdAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="最后登录">
            {{ formatDate(user.lastLoginAt) }}
          </el-descriptions-item>
        </el-descriptions>

        <div v-if="user.bio" class="user-bio">
          <h4>个人简介</h4>
          <p>{{ user.bio }}</p>
        </div>
      </el-card>

      <!-- 权限信息 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <h4>权限信息</h4>
        </template>
        <div class="permissions-list">
          <div
            v-for="permission in user.permissions"
            :key="permission"
            class="permission-item"
          >
            <el-tag size="small">{{ translatePermission(permission) }}</el-tag>
          </div>
        </div>
      </el-card>

      <!-- 通知设置 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <h4>通知设置</h4>
        </template>
        <div class="notifications-list">
          <el-tag
            v-for="notification in user.notifications"
            :key="notification"
            size="small"
            type="info"
            style="margin-right: 8px;"
          >
            {{ translateNotification(notification) }}
          </el-tag>
        </div>
      </el-card>

      <!-- 工单统计 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <h4>工单统计</h4>
        </template>
        <div class="ticket-stats">
          <div class="stat-item">
            <div class="stat-number">{{ getUserTicketCount(user.id) }}</div>
            <div class="stat-label">总工单数</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ getCompletedTicketCount(user.id) }}</div>
            <div class="stat-label">已完成</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ getPendingTicketCount(user.id) }}</div>
            <div class="stat-label">待处理</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ getCompletionRate(user.id) }}%</div>
            <div class="stat-label">完成率</div>
          </div>
        </div>
      </el-card>

      <!-- 最近活动 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <h4>最近活动</h4>
        </template>
        <el-timeline>
          <el-timeline-item
            v-for="activity in userActivities"
            :key="activity.id"
            :timestamp="formatDate(activity.createdAt)"
            :type="getActivityType(activity.type)"
          >
            <div class="activity-content">
              <div class="activity-action">{{ activity.description }}</div>
              <div v-if="activity.details" class="activity-details">
                {{ activity.details }}
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button
          v-if="canEditUser"
          type="primary"
          @click="handleEdit"
        >
          编辑用户
        </el-button>
        <el-button
          v-if="canManagePermissions"
          type="success"
          @click="handleManagePermissions"
        >
          管理权限
        </el-button>
        <el-dropdown @command="handleMoreActions">
          <el-button>
            更多操作<el-icon><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="resetPassword">重置密码</el-dropdown-item>
              <el-dropdown-item command="loginLog">登录日志</el-dropdown-item>
              <el-dropdown-item command="export">导出用户信息</el-dropdown-item>
              <el-dropdown-item
                v-if="canDeleteUser"
                command="delete"
                divided
              >
                删除用户
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { useAuthStore, PERMISSIONS } from '../store/auth'
import { useTicketsStore } from '../store/tickets'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'UserDetailDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    user: {
      type: Object,
      default: null
    }
  },
  emits: ['update:visible', 'update'],
  setup(props, { emit }) {
    const authStore = useAuthStore()
    const ticketsStore = useTicketsStore()
    const userActivities = ref([])

    // 权限检查
    const canEditUser = computed(() => {
      return authStore.hasPermission(PERMISSIONS.USER_MANAGE) &&
             authStore.user.id !== props.user?.id
    })

    const canManagePermissions = computed(() => {
      return authStore.hasPermission(PERMISSIONS.USER_MANAGE) &&
             authStore.user.id !== props.user?.id
    })

    const canDeleteUser = computed(() => {
      return authStore.hasPermission(PERMISSIONS.USER_MANAGE) &&
             authStore.user.id !== props.user?.id &&
             props.user?.role !== 'admin'
    })

    // 监听user变化，加载相关数据
    watch(() => props.user, async (newUser) => {
      if (newUser) {
        await loadUserActivities(newUser.id)
      }
    }, { immediate: true })

    // 加载用户活动
    const loadUserActivities = async (userId) => {
      try {
        // 这里应该调用API获取用户活动
        userActivities.value = [
          {
            id: 1,
            type: 'LOGIN',
            description: '用户登录系统',
            details: 'IP: 192.168.1.100',
            createdAt: new Date().toISOString()
          },
          {
            id: 2,
            type: 'TICKET_CREATE',
            description: '创建了工单 #1234',
            details: '工单标题：系统登录问题',
            createdAt: new Date(Date.now() - 3600000).toISOString()
          },
          {
            id: 3,
            type: 'TICKET_UPDATE',
            description: '更新了工单 #1234',
            details: '状态从"待处理"变更为"处理中"',
            createdAt: new Date(Date.now() - 7200000).toISOString()
          }
        ]
      } catch (error) {
        console.error('加载用户活动失败:', error)
      }
    }

    // 处理更多操作
    const handleMoreActions = (command) => {
      switch (command) {
        case 'resetPassword':
          resetPassword()
          break
        case 'loginLog':
          viewLoginLog()
          break
        case 'export':
          exportUserInfo()
          break
        case 'delete':
          deleteUser()
          break
      }
    }

    const resetPassword = async () => {
      try {
        await ElMessageBox.confirm(
          `确定要重置用户 "${props.user.name}" 的密码吗？`,
          '重置密码确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        ElMessage.success('密码重置成功，新密码已发送到用户邮箱')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('重置密码失败：' + error.message)
        }
      }
    }

    const viewLoginLog = () => {
      ElMessage.info('登录日志功能开发中...')
    }

    const exportUserInfo = () => {
      ElMessage.info('导出功能开发中...')
    }

    const deleteUser = async () => {
      try {
        await ElMessageBox.confirm(
          `确定要删除用户 "${props.user.name}" 吗？此操作不可撤销！`,
          '删除用户确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        ElMessage.success('用户删除成功')
        emit('update:visible', false)
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败：' + error.message)
        }
      }
    }

    // 处理编辑
    const handleEdit = () => {
      emit('update', { ...props.user, _edit: true })
      emit('update:visible', false)
    }

    // 处理权限管理
    const handleManagePermissions = () => {
      emit('update', { ...props.user, _managePermissions: true })
      emit('update:visible', false)
    }

    // 处理关闭
    const handleClose = () => {
      emit('update:visible', false)
    }

    // 工具方法
    const getRoleType = (role) => {
      const types = {
        admin: 'danger',
        manager: 'warning',
        agent: 'primary',
        customer: 'info'
      }
      return types[role] || 'info'
    }

    const getStatusType = (status) => {
      const types = {
        active: 'success',
        inactive: 'danger',
        suspended: 'warning'
      }
      return types[status] || 'info'
    }

    const getActivityType = (type) => {
      const types = {
        LOGIN: 'primary',
        TICKET_CREATE: 'success',
        TICKET_UPDATE: 'warning',
        USER_UPDATE: 'info'
      }
      return types[type] || 'info'
    }

    const translateRole = (role) => {
      const roleMap = {
        admin: '管理员',
        manager: '经理',
        agent: '客服',
        customer: '客户'
      }
      return roleMap[role] || role
    }

    const translateStatus = (status) => {
      const statusMap = {
        active: '激活',
        inactive: '禁用',
        suspended: '暂停'
      }
      return statusMap[status] || status
    }

    const translatePermission = (permission) => {
      const permissionMap = {
        'ticket:read': '查看工单',
        'ticket:create': '创建工单',
        'ticket:update': '更新工单',
        'ticket:delete': '删除工单',
        'ticket:assign': '指派工单',
        'user:manage': '用户管理',
        'system:config': '系统配置',
        'report:view': '报表查看'
      }
      return permissionMap[permission] || permission
    }

    const translateNotification = (notification) => {
      const notificationMap = {
        email: '邮件通知',
        sms: '短信通知',
        system: '系统通知',
        push: '推送通知'
      }
      return notificationMap[notification] || notification
    }

    const getUserTicketCount = (userId) => {
      return ticketsStore.tickets.filter(t => t.assigneeId === userId).length
    }

    const getCompletedTicketCount = (userId) => {
      return ticketsStore.tickets.filter(t => 
        t.assigneeId === userId && 
        (t.status === 'RESOLVED' || t.status === 'CLOSED')
      ).length
    }

    const getPendingTicketCount = (userId) => {
      return ticketsStore.tickets.filter(t => 
        t.assigneeId === userId && 
        t.status === 'OPEN'
      ).length
    }

    const getCompletionRate = (userId) => {
      const total = getUserTicketCount(userId)
      const completed = getCompletedTicketCount(userId)
      return total > 0 ? Math.round((completed / total) * 100) : 0
    }

    const formatDate = (dateString) => {
      if (!dateString) return '-'
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }

    return {
      userActivities,
      canEditUser,
      canManagePermissions,
      canDeleteUser,
      handleMoreActions,
      handleEdit,
      handleManagePermissions,
      handleClose,
      getRoleType,
      getStatusType,
      getActivityType,
      translateRole,
      translateStatus,
      translatePermission,
      translateNotification,
      getUserTicketCount,
      getCompletedTicketCount,
      getPendingTicketCount,
      getCompletionRate,
      formatDate
    }
  }
}
</script>

<style scoped>
.user-detail {
  max-height: 80vh;
  overflow-y: auto;
}

.detail-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-info h3 {
  margin: 0 0 12px 0;
  color: #303133;
}

.user-meta {
  display: flex;
  gap: 8px;
}

.user-bio {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.user-bio h4 {
  margin: 0 0 8px 0;
  color: #606266;
}

.user-bio p {
  margin: 0;
  color: #606266;
  line-height: 1.6;
}

.permissions-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.notifications-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.ticket-stats {
  display: flex;
  justify-content: space-around;
  gap: 20px;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

.activity-content {
  padding: 8px 0;
}

.activity-action {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.activity-details {
  color: #606266;
  font-size: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-dialog {
    width: 95% !important;
    margin: 0 auto;
  }
  
  .card-header {
    flex-direction: column;
    text-align: center;
  }
  
  .ticket-stats {
    flex-direction: column;
  }
  
  .permissions-list,
  .notifications-list {
    justify-content: center;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
}
</style>
